﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace LevelGenerator
{
    public class LvlGenerator
    {
        private int maxRoomSize = 300;
        private int minRoomSize = 100;
        private int numberOfRooms = 4;
        private List<Room> rooms = new List<Room>();
        private List<Corridor> corridors = new List<Corridor>();
        private int screenWidth;
        private int screenHeight;

        public LvlGenerator(int screenWidth, int screenHeight)
        {
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
        }

        public void Update(GameTime gametime, int screenWidth, int screenHeight)
        {
        }

        public List<Room> returnRooms()
        {
            return rooms;
        }
        public List<Corridor> returnCorridors()
        {
            return corridors;
        }

        public void ChangeCorridorColor(Color color)
        {
            corridors.ForEach(delegate(Corridor w)
            {
                w.color = color;
            });
        }

        public Level GenerateLevel()
        {
            rooms.Clear();
            corridors.Clear();
            for (int i = 0; i < numberOfRooms; i++)
            {
                GenerateRoom();
            }

            return new Level(rooms, corridors);
        }

        private void GenerateRoom()
        {
            bool collision;
            Room room;
            do
            {
                collision = false;
                //Generate room
                room = new Room(new Rectangle(0, 0, minRoomSize, minRoomSize), new Rectangle(screenWidth, screenHeight, 300, 300));


                //If There is no room to add the created to rooms

                if (rooms.Count == 0)
                    rooms.Add(room);
                else
                {
                    //Else check if the new room intersects with one of the excisting
                    rooms.ForEach(delegate(Room r)
                    {
                        //if The new room intersects don't add it and start with generating one again
                        if (room.ReturnBoundary().Intersects(r.ReturnBoundary()) || !room.ReturnOutlineBoundary().Intersects(r.ReturnBoundary()))
                            collision = true;
                    });
                }

            } while (collision == true);
            rooms.Add(room);
            if (rooms.Count > 1)
                corridors.Add(new Corridor(rooms[rooms.Count - 2].ReturnBoundary().Center, room.ReturnBoundary().Center));
        }
    }
}
